package com.ittx.dzt.meione.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.meione.handler.AbstractMeioneByTimeApiHandler;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 获取商品数据-V2
 * <p>
 * cy.sku.download.byTimeFrame
 * /erp/un/sys/goods/v2 获取商品数据-V2
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/9/1
 */
@Slf4j
@Service
public class MeioneSkuDownloadByTimeFrameService extends AbstractMeioneByTimeApiHandler<TimeFrameDTO> {

	private static final int DEFAULT_PAGE_SIZE = 100;

	@Autowired
	MeioneSkuDownloadBySpuIdService meioneSkuDownloadBySpuIdService;


	@Override
	public String getMqTopic() {
		return "";
	}

	@Override
	public String getMeioneMethod() {
		return "/erp/un/sys/goods/v2";
	}

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SKU_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	public Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		// 分发数据,异步下载
		Map<String, Boolean> logMap = new HashMap<>();
		// 判断是rds还是sdk
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);

	}

	@Override
	public Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//探查成功时不返回完整数据,只返回数量
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
	}

	@Override
	public Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		String productId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, productId);
	}

	/**
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		Map<String, Object> params = new HashMap<>();
		// 开始时间
		params.put("pageSize", DEFAULT_PAGE_SIZE);
		params.put("businessCode", DateUtil.format(timeFrameDTO.getFrom(), DatePattern.NORM_DATETIME_PATTERN));
		params.put("updateTimeStart", DateUtil.format(timeFrameDTO.getTo(), DatePattern.NORM_DATETIME_PATTERN));
		// 结束时间
		params.put("updateTimeEnd", timeFrameDTO.getTo().toEpochSecond(ZoneOffset.of("+8")));
		long page = 1;
		// 第一次查询，获取总页数 第一页为1
		params.put("pageNum", page);
		Result<?> result = this.executeApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
		if (result.hasError()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
		Map subDataMap = MapUtil.get(dataMap, "subData", Map.class);
		// 订单数量
		Integer total = MapUtil.getInt(subDataMap, "total");
		// 探查模式只返回总数
		if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
			return Result.success().addData(total);
		}
		// 总页数
		Integer totalPage = this.totalPage(total, DEFAULT_PAGE_SIZE);
		if (totalPage > 0) {
			// 倒序查询，防止数据遗漏
			for (int i = totalPage; i >= 1; i--) {
				params.put("pageNum", i);
				result = this.executeApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
				if (result.hasError()) {
					return result;
				}
				dataMap = (Map<String, Object>) resultMap.get("data");
				subDataMap = MapUtil.get(dataMap, "subData", Map.class);
				List<Map> recordsList = MapUtil.get(subDataMap, "records", List.class);
				if (CollUtil.isNotEmpty(recordsList)) {
					// 分发数据到MQ，异步消费下载
					for (Map<String, Object> product : recordsList) {
						String spuNo = MapUtil.getStr(product, "spuNo");
						Result sendResult = this.sendRequestToPlatform(platformApiParamDTO, product, true);
						if (sendResult.hasError()) {
							//分发到MQ失败
							logMap.put(spuNo, false);
						} else {
							logMap.put(spuNo, true);
						}
					}
				}
			}
		}
		return Result.success(logMap);
	}

	/**
	 * 多线程处理逻辑
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String productId) {
		Result<?> result = meioneSkuDownloadBySpuIdService.getProductById(productId, platformApiParamDTO);
		if (result.hasError()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}


}
